<template>
  <div style="float: left">
    <!--场景：-->
    <span v-if="title" style="margin-right: 5px">{{ title }}：</span>
    <a-select v-model="defaultValue" style="width: 150px; margin-right: 8px" @change="handleSceneId">
      <div slot="dropdownRender" slot-scope="menu">
        <v-nodes :vnodes="menu" />
      </div>
      <!-- <a-select-option key="0" value="0">    .</a-select-option> -->
      <a-select-option v-for="item in showSceneList" v-if="item.sceneId" :key="item.sceneId" :value="item.sceneId">
        {{ item.name }}
      </a-select-option>
      <a-select-option v-for="item in showSceneList" v-if="!item.sceneId" :key="item.value" :value="item.value">
        {{ item.name }}
      </a-select-option>
    </a-select>

    <oufu-scene
      :fieldList="fieldList"
      :sceneType="sceneType"
      ref="superQueryModal"
      @handleSceneQuery="handleSceneQuery"
    ></oufu-scene>

    <a-modal
      title="场景管理"
      :width="800"
      :visible="sliderTrans"
      @ok="saveSlider"
      @cancel="handleCancel"
      :mask="false"
      class="j-super-query-modal"
      style="top: 5%; max-height: 95%; border-bottom: none"
    >
      <a-transfer
        style="height: 300px"
        :listStyle="listStyle"
        :operations="operations"
        :titles="title"
        :data-source="mockData"
        :target-keys="targetKeys"
        :filter-option="(inputValue, item) => item.title.indexOf(inputValue) !== -1"
        :show-select-all="false"
        @change="onChange"
      >
        <template
          slot="children"
          slot-scope="{
            props: { direction, filteredItems, selectedKeys, disabled: listDisabled },
            on: { itemSelectAll, itemSelect },
          }"
        >
          <a-table
            :scroll="{ y: 200 }"
            :pagination="false"
            :columns="direction === 'left' ? leftColumns : rightColumns"
            :data-source="filteredItems"
            :row-selection="getRowSelection({ disabled: listDisabled, selectedKeys, itemSelectAll, itemSelect })"
            size="small"
            :style="{ pointerEvents: listDisabled ? 'none' : null }"
            :custom-row="
              ({ key, disabled: itemDisabled }) => ({
                on: {
                  click: () => {
                    if (itemDisabled || listDisabled) return
                    itemSelect(key, !selectedKeys.includes(key))
                  },
                },
              })
            "
          >
            <template slot="operation" slot-scope="text, record">
              <div class="editable-row-operations">
                <a-icon type="edit" @click="() => editScene(record.key)" />
                <a-icon style="margin-left: 10px" type="delete" @click="() => delScene(record.key)" />
              </div>
            </template>
          </a-table>
        </template>
      </a-transfer>
      <a-row class="plus">
        <a-button type="text" @click="addScene">+ 新建场景</a-button>
      </a-row>
    </a-modal>
  </div>
</template>

<script>
import difference from 'lodash/difference'
import { httpAction, getAction } from '@/api/manage'
import OufuScene from '@/components/jeecg/OufuScene.vue'

export default {
  name: 'OufuSceneSlider',
  components: {
    VNodes: {
      functional: true,
      render: (h, ctx) => ctx.props.vnodes,
    },
    OufuScene,
  },
  props: {
    title: {
      type: String,
      required: false,
      default(){
        return ''
      }
    },
    sceneType: {
      type: String,
      required: true,
    },
    columns: {
      type: Array,
      required: true,
    },
  },
  data() {
    return {
      leftColumns: [
        {
          dataIndex: 'title',
          title: '场景名称',
        },
        {
          title: ' ',
          dataIndex: 'operation',
          scopedSlots: { customRender: 'operation' },
        },
      ],
      rightColumns: [
        {
          dataIndex: 'title',
          title: '场景名称',
        },
        {
          title: ' ',
          dataIndex: 'operation',
          scopedSlots: { customRender: 'operation' },
        },
      ],
      operations: ['', ''],
      title1: ['显示的标签', '隐藏的标签'],
      listStyle: {
        width: '250px',
        height: '290px',
      },
      mockData: [],
      targetKeys: [],
      sliderTrans: false,

      fieldList: [],
      sceneId: '',
      sceneList: [],
      showSceneList: [],
      defaultValue: null,
      url: {
        sceneList: '/online/api/pagingCrmScene',
      },
      obj: {},
    }
  },
  created() {
    this.obj = this.$parent.$parent.$parent.$parent
    this.pagingCrmScene()
    //查询可搜索字段
    this.pagingCrmSceneField()
  },
  methods: {
    //场景新增代码开始
    handleCancel() {
      this.close()
    },
    async saveSlider() {
      let hideIds = []
      let noHideIds = []
      this.mockData.forEach((item) => {
        var index = this.targetKeys.findIndex((item2) => item2 === item.key)
        if (index == -1) {
          noHideIds.push(item.key)
        }
      })
      this.targetKeys.forEach((item) => {
        hideIds.push(item)
      })
      await getAction('/online/dict/updateSceneConfig', {
        type: this.sceneType,
        hideIds: hideIds,
        noHideIds: noHideIds,
      })
      this.pagingCrmScene()
      this.sliderTrans = false
    },
    editScene(val) {
      this.sliderTrans = false
      this.$refs.superQueryModal.sceneId = val
      this.$refs.superQueryModal.show()
    },
    async delScene(val) {
      await getAction('/online/api/deleteCrmScene', { sceneId: val })
      this.pagingCrmScene()
      this.getMock()
    },
    getMock() {
      const targetKeys = []
      const mockData = []
      this.sceneList.forEach((item, index) => {
        const data = {
          key: item.sceneId,
          title: item.name,
          description: item.name,
          isHide: item.isHide,
        }
        if (data.isHide == '1') {
          targetKeys.push(data.key)
        }
        mockData.push(data)
      })
      this.mockData = mockData
      this.targetKeys = targetKeys
      this.sliderTrans = true
    },
    onChange(nextTargetKeys) {
      this.targetKeys = nextTargetKeys
    },
    getRowSelection({ disabled, selectedKeys, itemSelectAll, itemSelect }) {
      return {
        getCheckboxProps: (item) => ({ props: { disabled: disabled || item.disabled } }),
        onSelectAll(selected, selectedRows) {
          const treeSelectedKeys = selectedRows.filter((item) => !item.disabled).map(({ key }) => key)
          const diffKeys = selected
            ? difference(treeSelectedKeys, selectedKeys)
            : difference(selectedKeys, treeSelectedKeys)

          itemSelectAll(diffKeys, selected)
          console.log(diffKeys, selected)
        },
        onSelect({ key }, selected) {
          itemSelect(key, selected)
          console.log(key, selected)
        },
        selectedRowKeys: selectedKeys,
      }
    },
    close() {
      this.$emit('close')
      this.sliderTrans = false
    },
    openSceneTrans() {
      this.getMock()
    },
    pagingCrmSceneField() {
      let superQueryFieldList = []
      this.columns.forEach((item) => {
        if (item.dataIndex) {
          ;(async () => {
            let value = item.dataIndex
            if (item.dictCode) {
              if (!item.type) item.type = 'select'
              if (item.dataIndex.indexOf('_dictText') >= 0) {
                value = item.dataIndex.substring(0, item.dataIndex.indexOf('_dictText'))
              }
            }
            if (!item.type) item.type = 'string'
            if (item.dataIndex != 'createUserId' && item.dataIndex != 'createTime' && item.dataIndex != 'updateTime') {
              superQueryFieldList.push({
                dictCode: item.dictCode,
                dictUrl: item.dictUrl,
                type: item.type,
                value: value,
                text: item.title,
              })
            }
          })()
        }
      })
      this.fieldList = superQueryFieldList
    },
    handleSceneId(val) {
      //清除高级搜索,使用场景ID查询
      this.$bus.emit('superParam', { type: 1, data: val })
    },

    handleSceneQuery(arg) {
      this.$bus.emit('superParam', { type: 2, data: arg })
      this.pagingCrmScene()
      this.$refs.superQueryModal.hide()
    },
    async pagingCrmScene() {
      this.showSceneList = []
      const res = await getAction(this.url.sceneList, { type: this.sceneType })
      this.sceneList = res.result
      this.sceneList.splice(this.sceneList.length)
      this.sceneList.forEach((item) => {
        if (item.isHide == '0') {
          if (item.default && item.default === 'Y') {
            this.defaultValue = item.value
          }
          this.$nextTick(() => {
            this.showSceneList.push(item)
          })
        }
      })
      this.handleSceneId(this.defaultValue)
    },
    openOufuScene() {
      this.$refs.superQueryModal.show()
    },
    addScene() {
      this.close()
      this.openOufuScene()
    },
    //场景新增代码结束
  },
}
</script>

<style lang="less" scoped>
/deep/ .ant-empty {
  display: none;
}
/deep/ .ant-modal-header {
  border-bottom: none;
  .ant-modal-title {
    font-weight: 700;
    font-size: 20px;
  }
}

/deep/ .ant-transfer-operation .ant-btn {
  border-radius: 50%;
  width: 35px;
  height: 35px;
}

.plus {
  /deep/ .ant-btn {
    border: none;
    padding: 0;
    box-shadow: none;
    color: #2362fb;
    transition: none;
    touch-action: none;
  }
}
</style>
